<?php
/**
 * Created by PhpStorm.
 * User: purelightme
 * Date: 2017/7/30
 * Time: 15:24
 */
$ws_server = new swoole_websocket_server('0.0.0.0', 8007);
$redis = new Redis();

//连接数据库
//include('db.php');
//$db =ConnectMysqli::getIntance();
//$list = $db->getAll("select * from webim_history");


$redis->connect('127.0.0.1', 6379);
$redis->flushAll();

$ws_server->on('open', function ($ws, $request) use ($redis) {
    $redis->sAdd('fd', $request->fd);
});

$ws_server->on('message', function ($ws, $frame) use ($redis) {
    global $redis;
    $fds = $redis->sMembers('fd');
    $data = json_decode($frame->data,true);
    var_dump($data);
    //设置用户标识 uid -> socket-id
    if(isset($data['uid'])){
        //保存用户的id  与系统连接id对应
        $redis->set($frame->fd,$data['uid']);
        //保存用的姓名  与 用户的id对应
        $redis->set($data['uid'],$data['name']);
        //获取用户列表
        getUserlist($ws,$redis);
    }
    $uid = $redis->get($frame->fd);
    //查找ruid对应的fid
    $ruid = '';
    if(isset($data['ruid'])){
        foreach ($fds as $fd){
            if($redis->get($fd) == $data['ruid']){
                $ruid = $fd;
                break;
            };
        }
        unset($fd);
    }

    //向指定用户发送信息
    if(isset($data['msg']) && in_array($ruid,$fds)){
        //向指定用户推送信息
        $ws->push($ruid,json_encode(['message'=>$data['msg'],'ruid'=>$uid,'uid'=>$data['ruid']]));
        //向自己推送信息
        $ws->push($frame->fd,json_encode(['message'=>$data['msg'],'ruid'=>$uid,'uid'=>$data['ruid']]));
    }else if(isset($data['msg'])){
        foreach ($fds as $fd){
            $ws->push($fd,json_encode(['message'=>$data['msg'],'ruid'=>$uid,'uid'=>$uid]));
            //发送二进制数据：
//        $ws->push($fd,file_get_contents('3456789'),WEBSOCKET_OPCODE_BINARY);
        }
    }
});

//监听WebSocket连接关闭事件
$ws_server->on('close', function ($ws, $fd) use ($redis) {
    //查询用户的id
    $uid = $redis->get($fd);
    //删除用户id对应的fid 及用户姓名
    $redis->delete($fd,$uid);
    $redis->sRem('fd',$fd);
    getUserlist($ws,$redis);

});

$ws_server->start();

//获取好友列表
function getUserlist($ws,$redis){
    $fds = $redis->sMembers('fd');
    $uid_arr =[];
    foreach ($fds as $k=>$fdd){
        //根据scoket_id  获取uid
        $uid_arr[$k]['uid']=$redis->get($fdd);
        $uid_arr[$k]['name']=$redis->get($uid_arr[$k]['uid']);
    }
    unset($fdd);
    //向所有人发信息
    foreach ($fds as $fdd){
        $ws->push($fdd,json_encode(['users'=>$uid_arr]));
    }
}
